package com.zking.web;

import com.zking.dao.domain.DateAndDoctor;
import com.zking.dao.domain.Department;
import com.zking.dao.domain.Doc_schedule;
import com.zking.dao.domain.Doctor;
import com.zking.service.DepartmentService;
import com.zking.service.DoctorService;
import com.zking.utils.DateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.common.Mapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.View;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

@Controller
@RequestMapping(value = "/doctor",name= "医生")
public class DoctorController {

    @Autowired
    private DoctorService doctorService;
    @Autowired
    private DepartmentService departmentService;
    DateUtil dateUtil = new DateUtil();



    @RequestMapping(value = "/showDoctors",name = "显示医生信息")
    @RequiresPermissions("doctor:showDoctors")
    public String show_All(Model model,Integer dept_id,String code){
        System.out.println("code="+code);
        List<Doctor> doctors_need = new ArrayList<>();
        //获取所有医生信息
        List<Doctor> doctors = doctorService.queryDoctors();
        //将路径的斜杠转化
        for (Doctor doctor : doctors) {
           int deptid = Integer.parseInt(doctor.getDeptid());
           //获取对应科室id的科室名
           doctor.setDeptid(departmentService.queryDepartment(deptid).getDeptName());
           doctor.setPpic(doctor.getPpic().replaceAll("\\\\", "/"));
           if (dept_id==null||dept_id==0){
               doctors_need.add(doctor);
           }else if(deptid == dept_id){
               doctors_need.add(doctor);
           }

        }
        if (doctors_need.size()>0){
            model.addAttribute("doctors_need",doctors_need);
            model.addAttribute("dept_id",dept_id);
            model.addAttribute("code",code);
        }
        return "backend_page/doctors";
    }

    /**
     * 转发至增加页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/add_jsp",name = "跳转增加医生页面")
    @RequiresPermissions("doctor:add_jsp")
    public String add_doctor_jsp(Model model){
        //获取科室
        List<Department> departments = doctorService.queryDepartments();
        //传递科室信息
        model.addAttribute("departments",departments);
        return "backend_page/add_doctor";
    }

    @RequestMapping(value="/add_doctor",method = RequestMethod.POST,name = "增加医生信息")
    @RequiresPermissions("doctor:add_doctor")
    public String add_doctor(Doctor doctor,@RequestParam("file") MultipartFile multipartFile,HttpServletRequest request){
        //得到该项目路径
        String filePath = request.getSession().getServletContext().getRealPath("uploadImg/");
        //上传
        String ppic = doctorService.upload(multipartFile,filePath);
        String str1=ppic.substring(0, ppic.indexOf("webapp"));
        String filePath2=ppic.substring(str1.length()+7, ppic.length());
        //将新的路径加入实体类中
        doctor.setPpic(filePath2.replaceAll("\\\\", "/"));
        int code = doctorService.insertDoctor(doctor);
        request.setAttribute("code",code);
        return "redirect:/department/showDepartments?code="+code;
    }


    /**
     * 删除医生信息
     */
    @RequestMapping(value = "/deleteDoctor",name = "删除医生信息")
    @RequiresPermissions("doctor:deleteDoctor")
    public String delete_doctor(int id,Model model,int dept_id){
        //System.out.println(id);
        //int code = 1;
        int code = doctorService.deleteDoctor(id);
        return "redirect:/doctor/showDoctors?code="+code+"&dept_id="+dept_id;
    }

    /**
     * 修改前查询单个医生信息
     */
    @RequestMapping(value = "queryDoctor",name = "查询单个医生信息")
    @RequiresPermissions("doctor:queryDoctor")
    public String query_doctor(int id,Model model,int dept_id){
        Doctor doctor = doctorService.queryDoctor(id);
        int deptid = Integer.parseInt(doctor.getDeptid());
        doctor.setDeptid(departmentService.queryDepartment(deptid).getDeptName());
        //获取科室
        List<Department> departments = doctorService.queryDepartments();

        //传递科室信息
        model.addAttribute("departments",departments);
        model.addAttribute("doctor",doctor);
        model.addAttribute("dept_id",dept_id);
        return "backend_page/update_doctor";
    }

    /**
     * 修改
     */
    @RequestMapping(value = "updateDoctor",name = "修改医生信息")
    @RequiresPermissions("doctor:updateDoctor")
    public String update_doctor(Doctor doctor,Model model,HttpServletRequest request,int dept_id){
        //得到该项目路径
        String filePath = request.getSession().getServletContext().getRealPath("uploadImg/");
        //String ppic = doctorService.upload(file,filePath);
//        String str1=ppic.substring(0, ppic.indexOf("webapp"));
//        String filePath2=ppic.substring(str1.length()+7, ppic.length());
        //将新的路径加入实体类中
        //doctor.setPpic(filePath2);
        String filePath3 = request.getSession().getServletContext().getRealPath("uploadImg/");
        int code = doctorService.updateDoctor(doctor);
        model.addAttribute("code",code);
        model.addAttribute("dept_id",dept_id);
        return "redirect:/doctor/showDoctors?code="+code+"&dept_id="+dept_id;
    }


    @RequestMapping(value = "/schedule",name = "科室排班管理")
    @RequiresPermissions("doctor:schedule")
    public String doc_schedule(int dept_id,Model model){
        List<Doctor> doctors = doctorService.department_doctor(dept_id);
        List<String> dateList = dateUtil.getWeekDay();
        String eight_day = dateUtil.getEightDay();
        List<Doc_schedule> doc_schedules =  doctorService.query_Schedules(dept_id);
        List<DateAndDoctor> dateAndDoctors = new ArrayList<>();
        for (Doc_schedule doc_schedule : doc_schedules) {
            if (doc_schedule.getTimeInterval()==1){
                dateAndDoctors.add(new DateAndDoctor(doc_schedule.getDid(),doc_schedule.getDname(),doc_schedule.getDaytime(),1));
            }else if(doc_schedule.getTimeInterval()==2){
                dateAndDoctors.add(new DateAndDoctor(doc_schedule.getDid(),doc_schedule.getDname(),doc_schedule.getDaytime(),2));
            }else if(doc_schedule.getTimeInterval()==3){
                dateAndDoctors.add(new DateAndDoctor(doc_schedule.getDid(),doc_schedule.getDname(),doc_schedule.getDaytime(),3));
            }
        }
        model.addAttribute("doctors",doctors);
        model.addAttribute("dept_id",dept_id);
        model.addAttribute("dateList",dateList);
        model.addAttribute("eight_day",eight_day);
        model.addAttribute("dateAndDoctors",dateAndDoctors);
        return "backend_page/doctor_schedule";
    }

    @RequestMapping(value = "/dateDoctor",name = "修改排班信息")
    @RequiresPermissions("doctor:dateDoctor")
    public String dateDoctor(String[] time_morning,String[] time_afternoon ,Integer dept_id,Model model) {
        List<DateAndDoctor> dateAndDoctors= new ArrayList<>();
        List<String> strs = null;
        //需要修改的时间
        String update_time = dateUtil.getEightDay();
        strs = Arrays.asList(Arrays.toString(time_morning).replace("[","").replace("]","").replace(" ","").split(","));
        for (int i = 0;i<strs.size();i+=2){
            if (strs.size()!=1){
                dateAndDoctors.add(new DateAndDoctor(Integer.parseInt(strs.get(i)),strs.get(i+1),update_time,1));
            }
        }
        strs = Arrays.asList(Arrays.toString(time_afternoon).replace("[","").replace("]","").replace(" ","").split(","));
        for (int i = 0;i<strs.size();i+=2){
            if (strs.size()!=1) {
                dateAndDoctors.add(new DateAndDoctor(Integer.parseInt(strs.get(i)), strs.get(i + 1), update_time, 2));
            }
        }
        System.out.println(doctorService.updateSchedule(dateAndDoctors,dept_id,update_time));
        model.addAttribute("dept_id",dept_id);

        return "redirect:/doctor/showDoctors?dept_id="+dept_id;
    }






    /**
     * 显示图片
     * @param response
     * @throws IOException
     */
//    @RequestMapping("/showImg")
//    private void showAddressImage( HttpServletResponse response,String path)throws IOException
//    {
//        //转化为字节输入流
//        File file = new File(path);
//        if (file != null && file.exists()) {
//            InputStream in;
//            in = new FileInputStream(file);
//            //获取response相应的输出流
//            //一个请求request--->相应response
//            OutputStream out = response.getOutputStream();
//            //将这个图片的字节直接写到前端
//            int len = 0;
//            byte[] b = new byte[1024];
//            while ((len = in.read(b)) != -1) {
//                out.write(b, 0, len);
//            }
//            //关闭资源
//            out.flush();
//            out.close();
//            in.close();
//            //刷新一下响应的缓存
//            response.flushBuffer();
//        }
//    }
}
